package my.diplom.web.validators;

import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.apache.log4j.Logger;
import my.diplom.entity.Application;
import my.diplom.entity.Resource;
import my.diplom.util.HostUtil;

import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 17.09.2009
 * Time: 0:00:14
 * To change this template use File | Settings | File Templates.
 */
public class CreateResourceValidator implements Validator {

    private static final Logger log = Logger.getLogger(CreateResourceValidator.class);


    public boolean supports(Class clazz) {
        return Resource.class.equals(clazz);
    }

    @Override
    public void validate(Object o, Errors errors) {
        log.debug("validate resource" + o);
        Resource resource = (Resource) o;
        if (resource == null) errors.reject("Null data received");

        if (!HostUtil.isValidResource(resource.getHost(), resource)) {
            errors.reject("wrong resource", "wrong resource");
            System.out.println("Wrong resource!");
        }

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "hostName", "hostName.empty", "host Name is required");
        if (resource.getHostName().length() > 250) errors.rejectValue("hostName", "lenght is too long!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "ipAddress", "ipAddress.empty", "ip address is required");
        if (!isValidAddress(resource.getIpAddress())) errors.rejectValue("ipAddress", "ip.wrong", "address is wrong!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "login.empty", "Login is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.empty", "Password is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cpu", "cpu.empty", "PCU is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "hdd", "hdd.empty", "HDD is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "ram", "ram.empty", "RAM is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startDate", "startDate.empty", "startDate is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "finishDate", "finishDate.empty", "finishDate is required");


    }

    private boolean isValidAddress(String address){
        Pattern pattern = 
        Pattern.compile("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
        return pattern.matcher(address).matches();
    }



}
